# 主界面
from tkinter import Listbox, StringVar
from tkinter.ttk import Frame, Button, Entry, Label
from .style import PADDING
from .edit_bookmark import BookmarkDialog
from .edit_tag import TagDialog
from ..store.tag import list_tags, get_tag_by_name, delete_tag
from ..store.bookmark import list_bookmarks, get_bookmark_by_name, delete_bookmark
from ..store.search import search_bookmark
from .event_bus import Event, register_handler, send_event
from .event_bus import ETYPE_TAG_CHANGED, ETYPE_BOOKMARK_CHANGED
import webbrowser

class MainFrame(Frame):
    """ 主菜单 """
    def __init__(self, master=None):
        super().__init__(master)
        self.master.title("书签管理器")
        self.master.resizable(False, False)
        # 搜索条
        frame_search_bar = Frame(self)
        self.search_text_var = StringVar()
        self.search_text_var.set("")
        entry_search_text = Entry(frame_search_bar, width=80, textvariable=self.search_text_var)
        entry_search_text.pack(side="left", padx=0, pady=0)
        entry_search_text.bind("<Return>", self.search)
        btn_search = Button(frame_search_bar, text="搜索", command=self.search)
        btn_search.pack(side="left", padx=(PADDING, 0), pady=0, fill="x")
        frame_search_bar.pack(side="top", padx=PADDING, pady=(PADDING, 0), fill="x")
        # 标签操作面板
        frame_tag_panel = Frame(self)
        text_tag_panel = Label(frame_tag_panel, text="标签")
        text_tag_panel.pack(side="top", padx=PADDING, pady=0, fill="x")
        # 标签列表
        self.list_tags = Listbox(frame_tag_panel, width=26)
        self.list_tags.pack(side="top", padx=(PADDING, 0), pady=0, fill="both")
        self.list_tags.bind("<Double-Button-1>", self.use_tag)
        # 标签操作按钮
        frame_tag_buttons_panel_1 = Frame(frame_tag_panel)
        btn_tag_use = Button(frame_tag_buttons_panel_1, text="使用标签", command=self.use_tag)
        btn_tag_use.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        btn_tag_add = Button(frame_tag_buttons_panel_1, text="添加标签", command=self.add_tag)
        btn_tag_add.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        frame_tag_buttons_panel_1.pack(side="top", padx=0, pady=(PADDING, 0), fill="x")
        frame_tag_buttons_panel_2 = Frame(frame_tag_panel)
        btn_tag_edit = Button(frame_tag_buttons_panel_2, text="编辑标签", command=self.edit_tag)
        btn_tag_edit.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        btn_tag_del = Button(frame_tag_buttons_panel_2, text="删除标签", command=self.delete_tag)
        btn_tag_del.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        frame_tag_buttons_panel_2.pack(side="top", padx=0, pady=PADDING, fill="x")
        frame_tag_panel.pack(side="left", padx=0, pady=0, expand=0)
        # 书签管理面板
        frame_bookmark_panel = Frame(self)
        text_bookmark_panel = Label(frame_bookmark_panel, text="书签")
        text_bookmark_panel.pack(side="top", padx=PADDING, pady=0, fill="x")
        # 书签列表
        self.list_bookmarks = Listbox(frame_bookmark_panel, width=64)
        self.list_bookmarks.pack(side="top", padx=PADDING, pady=0, fill="both", expand=1)
        self.list_bookmarks.bind("<Double-Button-1>", self.use_bookmark)
        # 书签操作按钮
        frame_bookmark_buttons_panel = Frame(frame_bookmark_panel)
        btn_bookmark_view = Button(frame_bookmark_buttons_panel, text="查看书签", command=self.use_bookmark)
        btn_bookmark_view.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        btn_bookmark_add = Button(frame_bookmark_buttons_panel, text="添加书签", command=self.add_bookmark)
        btn_bookmark_add.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        btn_bookmark_edit = Button(frame_bookmark_buttons_panel, text="编辑书签", command=self.edit_bookmark)
        btn_bookmark_edit.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        btn_bookmark_del = Button(frame_bookmark_buttons_panel, text="删除书签", command=self.delete_bookmark)
        btn_bookmark_del.pack(side="left", padx=(PADDING, 0), pady=0, expand=0)
        frame_bookmark_buttons_panel.pack(side="bottom", padx=0, pady=PADDING, fill="x")
        frame_bookmark_panel.pack(side="right", padx=0, pady=0, fill="both")
        self.pack()
        # 初始化更新数据
        self.update_tag_list()
        self.update_bookmark_list()
        # 注册事件回调
        register_handler(self.on_event)
    
    def on_event(self, evt: Event):
        if evt.t == ETYPE_TAG_CHANGED:
            self.update_tag_list()
        elif evt.t == ETYPE_BOOKMARK_CHANGED:
            self.update_bookmark_list()

    def update_tag_list(self):
        self.list_tags.delete(0, self.list_tags.size() - 1)
        for tag in list_tags():
            self.list_tags.insert(self.list_tags.size(), tag.name)
    
    def update_bookmark_list(self):
        self.list_bookmarks.delete(0, self.list_bookmarks.size() - 1)
        for bmk in list_bookmarks():
            self.list_bookmarks.insert(self.list_bookmarks.size(), bmk.name)

    # ======== ↓按钮的回调方法↓ ========
    def use_tag(self, _event=None):
        if self.list_tags.curselection():
            name = self.list_tags.get(self.list_tags.curselection()[0])
            text = self.search_text_var.get()
            text += " "
            text += name
            self.search_text_var.set(text)
    
    def add_tag(self, _event=None):
        dlg = TagDialog(self) # block until closed
    
    def edit_tag(self, _event=None):
        if self.list_tags.curselection():
            name = self.list_tags.get(self.list_tags.curselection()[0])
            tag = get_tag_by_name(name)
            dlg = TagDialog(self, tag)
    
    def delete_tag(self, _event=None):
        if self.list_tags.curselection():
            name = self.list_tags.get(self.list_tags.curselection()[0])
            tag = get_tag_by_name(name)
            delete_tag(tag.uid)
            # 通知标签发生了更改 (删除标签时书签也可能发生了变化)
            send_event(Event(t=ETYPE_TAG_CHANGED))
            send_event(Event(t=ETYPE_BOOKMARK_CHANGED))

    def use_bookmark(self, _event=None):
        if self.list_bookmarks.curselection():
            name = self.list_bookmarks.get(self.list_bookmarks.curselection()[0])
            bmk = get_bookmark_by_name(name)
            webbrowser.open(bmk.value)

    def add_bookmark(self, event=None):
        dlg = BookmarkDialog(self)

    def edit_bookmark(self, _event=None):
        if self.list_bookmarks.curselection():
            name = self.list_bookmarks.get(self.list_bookmarks.curselection()[0])
            bmk = get_bookmark_by_name(name)
            dlg = BookmarkDialog(self, bmk)
    
    def delete_bookmark(self, _event=None):
        if self.list_bookmarks.curselection():
            name = self.list_bookmarks.get(self.list_bookmarks.curselection()[0])
            bmk = get_bookmark_by_name(name)
            delete_bookmark(bmk.uid)
            # 通知书签发生了更改
            send_event(Event(t=ETYPE_BOOKMARK_CHANGED))
    
    def search(self, _event=None):
        search_text = self.search_text_var.get().strip()
        if len(search_text) <= 0:
            # 空搜索的时候显示所有书签
            self.update_bookmark_list()
            return
        # 执行搜索
        bmks = search_bookmark(search_text)
        # 更新书签列表
        self.list_bookmarks.delete(0, self.list_bookmarks.size() - 1)
        for bmk in bmks:
            self.list_bookmarks.insert(self.list_bookmarks.size(), bmk.name)